package weixin

import (
	"context"
	"encoding/json"
	"fmt"
	"gitee.com/filters/utils/errv"
	"gitee.com/filters/utils/httpv"
	"time"
)

var (
	NotFoundErrCode = errv.New(10001, "状态码不存在")
)



type QiWxer struct {
	appid  string
	secret string
	token  string
}
type Options func(wxer *QiWxer)

func WithQSecret(secret string) Options {
	return func(wxer *QiWxer) {
		wxer.secret = secret
	}
}

func WithQAppid(appid string) Options {
	return func(wxer *QiWxer) {
		wxer.appid = appid
	}
}

func WithQToken(token string) Options {
	return func(wxer *QiWxer) {
		wxer.token = token
	}
}

//NewQWx 初始化
func NewQWx(opt ...Options) *QiWxer {
	wx := &QiWxer{}
	for _, option := range opt {
		option(wx)
	}
	return wx
}

type QiWxInfo struct {
	Errcode    int32  `json:"errcode"`
	Errmsg     string `json:"errmsg"`
	AccessToken string `json:"access_token"`
	ExpireIn int64 `json:"expire_in"`
}


//AccessToken ...
func (w *QiWxer) AccessToken() (string,error) {
	ctx := context.Background()
	var token string
	ctx, cancel := context.WithDeadline(ctx, time.Now().Add(5*time.Second))
	defer cancel()
	url := fmt.Sprintf(QiAccessTokenUrl, QWxBaseUrl, w.appid, w.secret)
	result, err := httpv.HttpGet(ctx, url, map[string]string{})
	if err != nil {
		return token, err
	}
	var data QiWxInfo
	err = json.Unmarshal(result,&data)
	if err!= nil {
		return token, err
	}
	if data.Errcode != 0 {
		return token, NotFoundErrCode
	}
	return data.AccessToken, nil
}